<template>
  <BasicModal v-bind="$attrs" @register="registerRoleListModal" title="选择角色" @ok="handleSubmit">
    <BasicTable @register="registerTable" />
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, nextTick, toRaw } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { Select, Row, Col, Table } from 'ant-design-vue';
  import { BasicTable, useTable } from '/@/components/Table';
  import { getRoleListByPage } from '/@/api/system/system';
  import { roleColumns, searchFormSchema } from './message.data';

  export default defineComponent({
    name: 'MessageRoleList',
    components: {
      BasicModal,
      BasicTable,
      [Select.name]: Select,
      [Row.name]: Row,
      [Col.name]: Col,
      [Table.name]: Table,
    },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const [registerTable, { getSelectRows, clearSelectedRowKeys, setSelectedRowKeys }] = useTable(
        {
          rowKey: 'roleCode',
          title: '角色列表',
          api: getRoleListByPage,
          columns: roleColumns,
          formConfig: {
            labelWidth: 120,
            schemas: searchFormSchema,
          },
          rowSelection: {
            type: 'checkbox',
          },
          canResize: false,
          maxHeight: 600,
          useSearchForm: true,
          showTableSetting: true,
          bordered: true,
          showIndexColumn: false,
        }
      );

      const [registerRoleListModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
        nextTick(() => {
          setModalProps({ confirmLoading: false, maskClosable: false, width: 960 });
          if (data.roleCodes) {
            setSelectedRowKeys(toRaw(data.roleCodes));
          }
        });
      });

      async function handleSubmit() {
        try {
          closeModal();
          emit('success', getSelectRows());
          clearSelectedRowKeys();
        } finally {
          setModalProps({ confirmLoading: false });
        }
      }

      return {
        registerRoleListModal,
        registerTable,
        handleSubmit,
      };
    },
  });
</script>
